<?php

/**
 * This is the model class for table "shift_change".
 *
 * The followings are the available columns in table 'shift_change':
 * @property integer $idshift_change
 * @property integer $requesting_user
 * @property integer $current_shift
 * @property integer $requested_shift
 * @property integer $requested_qshift
 * @property string $day_requested
 * @property integer $request_status
 * @property integer $target_user
 * @property string $comments
 * @property integer $team_id
 * @property string $is_swap
 * @property string $require_acct_approval
 * @property string $accounting_approved
 *
 * The followings are the available model relations:
 * @property Team $team
 * @property Shift $currentShift
 * @property Shift $requestedShift
 * @property User $requestingUser
 * @property User $targetUser
 * @property Qshift $requestedQshift
 */
class ShiftChange extends CActiveRecord
{

	const STATUS_APPROVED = 1;
	const STATUS_DENIED = 2;
	const STATUS_PENDING = 3;
	const STATUS_PENDING_CANCEL = 4;
	const STATUS_CANCELLED = 5;

	
     public $_weekday;

     public function getWeekday(){
         return $this->_weekday;
     }

     public function setWeekday($weekday){
         $this->_weekday = $weekday;
     }
	
	public static $status= array('1'=>'Approved', '2'=>'Denied','3'=>'Pending','4'=>'Pending Cancel','5'=>'Cancelled');

	public $yesNoValues= array('0'=>'No', '1'=>'Yes');

	 public function getYesNoValue($bin=null){
	 
		if($bin!==null)
			return $this->yesNoValues[$bin];
		return $this->yesNoValues[$this->is_swap];
	 }	
	
	 public static function getStatus($status=null){
	 
		if($status!==null)
			return self::$status[$status];
		return self::$status;
	 }	
	 
	 	
	 public function getStatusValue($status=null){
	 
		if($status!==null)
			return $this->status[$status];
		return $this->status[$this->request_status];
	 }	 
	 
	
	 public function isStatusCancellable($reqDate) {
	 
		$modelStatus = $this->request_status;
		
		$dateObject = new DateTime('NOW');
		$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));	
		$timestamp = strtotime($dateObject->format('Y-m-d'));
		
		if(strtotime($reqDate) < $timestamp)
			return false;
		
		if( ($modelStatus == ShiftChange::STATUS_APPROVED) or ($modelStatus == ShiftChange::STATUS_PENDING) )
			return true;
		else
			return false;
	 }	
		
	 public function canApproveDeny($reqDate) {
	 
		$modelStatus = $this->request_status;
		
		$dateObject = new DateTime('NOW');
		$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));	
		$timestamp = strtotime($dateObject->format('Y-m-d'));
		
		if(strtotime($reqDate) < $timestamp)
			return false;
		
		if( ($modelStatus == ShiftChange::STATUS_PENDING_CANCEL) or ($modelStatus == ShiftChange::STATUS_PENDING) )
			return true;
		else
			return false;
	 }	
	
	 public function getTargetUser(){
	 
		if($this->target_user!==null)
			return $this->targetUser_relation->username;
		return "---";
	 }		
	 
	 public function getCurrentShift(){
	 
		if($this->current_shift!==null)
			return $this->currentShift_relation->name;
		return "---";
	 }	
		
	 public function getTargetUserFullName(){
	 
		if($this->target_user!==null)
			return $this->targetUser_relation->fullname;
		return "---";
	 }	
	
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return ShiftChange the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'shift_change';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('requesting_user, requested_shift, requested_qshift, day_requested, request_status, team_id', 'required'),
			array('requesting_user, current_shift, requested_shift, requested_qshift, request_status, target_user, team_id', 'numerical', 'integerOnly'=>true),
			array('comments', 'length', 'max'=>100),
			array('day_requested', 'checkIfDateAvailable'),
			array('target_user', 'checkTargetUser'),
			array('requested_qshift', 'checkTargetShiftQshift'),
			array('requested_shift', 'checkTargetShift'),
			array('is_swap, require_acct_approval, accounting_approved', 'length', 'max'=>1),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('idshift_change, requesting_user, current_shift, requested_shift, requested_qshift, day_requested, request_status, target_user, comments, team_id, is_swap, require_acct_approval, accounting_approved', 'safe', 'on'=>'search'),
		);
	}

	/** function to check the shift hours (start/end time) exist within
	*	the start/end time of the Shift hours and that the qshift is enabled and allows changes
	*/	
	public function checkTargetShift($attribute,$params) {
	
		$shiftModel = Shift::model()->findByPk($this->requested_shift);
		
		if( $shiftModel != null ) {
		
			if( (!($shiftModel->enabled)) || (!($shiftModel->changes_allowed)) ) {
				$this->addError('requested_shift','<b>Error:</b> The <b>selected Shift is not enabled or it doesn\'t allow changes.'
								);
			}
		}
	}
	
	/** function to check the Qshift hours (start/end time) exist within
	*	the start/end time of the Shift hours and that the qshift is enabled and allows changes
	*/	
	public function checkTargetShiftQshift($attribute,$params) {
	
		$shiftModel = Shift::model()->findByPk($this->requested_shift);
		$qshiftModel = QShift::model()->findByPk($this->requested_qshift);
		
		if( ($shiftModel != null) && ($qshiftModel != null) ) {
		
			if( ($qshiftModel->enabled)) {
		
				if(!( ( strtotime($qshiftModel->start_time) >= strtotime($shiftModel->start_time) )
					&& 
					( strtotime($qshiftModel->end_time) <= strtotime($shiftModel->end_time) ) )) 
				{
					
					$this->addError('requested_qshift','<b>Error:</b> The <b>selected Q-Shift\'s hours</b> are <b>outside the Start/End times</b> of the <b>selected Shift!</b>');			
				}
			} else {
				$this->addError('requested_qshift','<b>Error:</b> The <b>selected Q-Shift is not enabled.');
			}
		}
	}
	
	/*
	* checks target for restrictions 
	*/	
	public function checkTargetUser($attribute,$params){
	
		if($this->requesting_user == $this->target_user)
			$this->addError('target_user','Well, for obvious reasons... you can\'t change with yourself buddy! :-D');	
		else {
			if ( $this->target_user != null) {
				
				$scheduleModel = Schedule::getUserScheduleForDate($this->target_user, $this->day_requested);
				
				if($scheduleModel == null){
					$this->addError('target_user','The target user doesn\'t have a schedule assigned for that day of the week!');
				}
			}
		}
	}	
	
		
	/*
	* checks if the a ShiftChange for this user for this day already exists
	*/	
	public function checkIfDateAvailable($attribute,$params){
		
		$criteria=new CDbCriteria;
		$criteria->condition = "day_requested like '".$this->day_requested."' \n
								and (request_status <> ". ShiftChange::STATUS_CANCELLED ." and request_status <> ". ShiftChange::STATUS_DENIED.") \n
								and (requesting_user = '".$this->requesting_user."' or target_user = '".$this->requesting_user."')";		
		
		$changeExists = ShiftChange::model()->findAll($criteria);
		
		//print_r($changeExists);exit;

		if(!$changeExists==null)
			$this->addError('day_requested','You already have a Shift Change approved or pending for this date!');	
	}	
	
	
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'requestingUser_relation' => array(self::BELONGS_TO, 'User', 'requesting_user'),
			'currentShift_relation' => array(self::BELONGS_TO, 'Shift', 'current_shift'),
			'requestedShift_relation' => array(self::BELONGS_TO, 'Shift', 'requested_shift'),
			'team_relation' => array(self::BELONGS_TO, 'Team', 'team_id'),
			'requestedQshift_relation' => array(self::BELONGS_TO, 'Qshift', 'requested_qshift'),
			'targetUser_relation' => array(self::BELONGS_TO, 'User', 'target_user'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'idshift_change' => 'Idshift Change',
			'requesting_user' => 'Requesting User',
			'current_shift' => 'Requestor\'s Shift',
			'requested_shift' => 'Requested Shift',
			'requested_qshift' => 'Requested Q-Shift',
			'day_requested' => 'Day Requested',
			'request_status' => 'Status',
			'target_user' => 'Target User',
			'comments' => 'Comments',
			'team_id' => 'Team',
			'is_swap' => 'Is Swap?',
			'yesNoValue' => 'Is Swap?',
			'statusValue' => 'Status',
			'require_acct_approval' => 'Requires Accouting Approval',
			'accounting_approved' => 'Accouting Approved',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$currentUser = User::model()->findByAttributes(array('username'=>Yii::app()->user->id))->iduser;
		
		$criteria=new CDbCriteria;
		
		$criteria->condition = 'requesting_user = "' . $currentUser . '" or target_user= "' . $currentUser .'"';
		$criteria->compare('idshift_change',$this->idshift_change);
		$criteria->compare('requesting_user',$this->requesting_user);
		$criteria->compare('current_shift',$this->current_shift);
		$criteria->compare('requested_shift',$this->requested_shift);
		$criteria->compare('requested_qshift',$this->requested_qshift);
		$criteria->compare('day_requested',$this->day_requested,true);
		$criteria->compare('request_status',$this->request_status);
		$criteria->compare('target_user',$this->target_user);
		$criteria->compare('is_swap',$this->is_swap);
		$criteria->order = 'day_requested DESC';
		//$criteria->compare('comments',$this->comments,true);
		//$criteria->compare('team_id',$this->team_id);
		

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function swapSearch()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$currentUser = User::model()->findByAttributes(array('username'=>Yii::app()->user->id))->iduser;
		
		$criteria=new CDbCriteria;
		
		$criteria->condition = '(requesting_user = "' . $currentUser . '" or target_user= "' . $currentUser .'") and is_swap = 1';
		$criteria->compare('idshift_change',$this->idshift_change);
		$criteria->compare('requesting_user',$this->requesting_user);
		$criteria->compare('current_shift',$this->current_shift);
		$criteria->compare('requested_shift',$this->requested_shift);
		$criteria->compare('requested_qshift',$this->requested_qshift);
		$criteria->compare('day_requested',$this->day_requested,true);
		$criteria->compare('request_status',$this->request_status);
		$criteria->compare('target_user',$this->target_user);
		$criteria->compare('is_swap',$this->is_swap);
		$criteria->order = 'day_requested DESC';
		//$criteria->compare('comments',$this->comments,true);
		//$criteria->compare('team_id',$this->team_id);
		

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function managementSearch($team_id=null)
	{

		//echo $team_id;exit;
		
		$criteria=new CDbCriteria;
		
		if($team_id != null)
			$criteria->condition = 'team_id = '.$team_id;					
		
		$criteria->condition = 'request_status = '. ShiftChange::STATUS_PENDING . ' or request_status = '. ShiftChange::STATUS_PENDING_CANCEL;
		$criteria->compare('idshift_change',$this->idshift_change);
		$criteria->compare('requesting_user',$this->requesting_user);
		$criteria->compare('current_shift',$this->current_shift);
		$criteria->compare('requested_shift',$this->requested_shift);
		$criteria->compare('requested_qshift',$this->requested_qshift);
		$criteria->compare('day_requested',$this->day_requested,true);
		$criteria->compare('request_status',$this->request_status);
		$criteria->compare('target_user',$this->target_user);
		//$criteria->compare('comments',$this->comments,true);
		$criteria->compare('team_id',$this->team_id);
		$criteria->order = 'day_requested ASC';
		

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}	
	
	public function reportingSearch()
	{
		$criteria=new CDbCriteria;
		
		$criteria->condition = 'team_id = '. Yii::app()->user->team_id;		
			
		$criteria->compare('idshift_change',$this->idshift_change);
		$criteria->compare('requesting_user',$this->requesting_user);
		$criteria->compare('current_shift',$this->current_shift);
		$criteria->compare('requested_shift',$this->requested_shift);
		$criteria->compare('requested_qshift',$this->requested_qshift);
		$criteria->compare('day_requested',$this->day_requested,true);
		$criteria->compare('request_status',$this->request_status);
		$criteria->compare('target_user',$this->target_user);
		//$criteria->compare('comments',$this->comments,true);
		$criteria->compare('team_id',$this->team_id);
		$criteria->compare('is_swap',$this->is_swap,true);
		$criteria->compare('require_acct_approval',$this->require_acct_approval,true);
		$criteria->compare('accounting_approved',$this->accounting_approved,true);		
		$criteria->order = 'day_requested DESC';
		

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function accountingApprovalSearch($team_id=null)
	{
		//echo $team_id;exit;
		
		$criteria=new CDbCriteria;
		
		if($team_id != null)
			$criteria->condition = 'team_id = '.$team_id;					
		
		$criteria->condition = 'request_status = '. ShiftChange::STATUS_APPROVED 
							  .' and require_acct_approval = 1'
							  .' and accounting_approved <> 1';
		$criteria->compare('idshift_change',$this->idshift_change);
		$criteria->compare('requesting_user',$this->requesting_user);
		$criteria->compare('current_shift',$this->current_shift);
		$criteria->compare('requested_shift',$this->requested_shift);
		$criteria->compare('requested_qshift',$this->requested_qshift);
		$criteria->compare('day_requested',$this->day_requested,true);
		$criteria->compare('request_status',$this->request_status);
		$criteria->compare('target_user',$this->target_user);
		//$criteria->compare('comments',$this->comments,true);
		$criteria->compare('team_id',$this->team_id);
		$criteria->order = 'day_requested ASC';
		

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}		
	
}